package com.xunyji.xunyjitest.web.weixin;

import com.xunyji.xunyjitest.comm.TransformUtils;
import com.xunyji.xunyjitest.comm.enums.weixin.MessageTypeEnum;
import com.xunyji.xunyjitest.comm.util.weixin.CheckUtil;
import com.xunyji.xunyjitest.comm.util.weixin.MessageUtils;
import com.xunyji.xunyjitest.model.weixin.param.ConnectParam;
import com.xunyji.xunyjitest.service.ReceiveMessageService;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.DocumentException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

/**
 * @author AltEnter
 * @create 2019-01-08 22:19
 * @desc 开发者接口
 **/
@RestController
@RequestMapping(value = "/weixin")
@Slf4j
public class WeixinController {

    @Autowired
    private CheckUtil checkUtil;

    @Autowired
    private ReceiveMessageService receiveMessageService;

    @GetMapping
    public void connect(HttpServletRequest request, HttpServletResponse response) throws IOException {
//        TODO: 接入逻辑
//        01 参数获取与封装
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");
        ConnectParam connectParam = ConnectParam.builder()
                .signature(signature)
                .timestamp(timestamp)
                .nonce(nonce)
                .echostr(echostr)
                .build();
        log.info(String.format("微信接入是微信平台发送过来的信息为：%s", connectParam));

        PrintWriter out = response.getWriter();

//        02 调用接入校验方法进行校验并返回校验结果
        if (checkUtil.checkSignature(connectParam)) {
            out.println(echostr);
        }
    }

    @PostMapping
    public void receiveMessage(HttpServletRequest request, HttpServletResponse response) throws IOException, DocumentException {
//        01 请求、响应编码格式设定
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

//        02 获取输出对象
        PrintWriter out = response.getWriter();
//        03 获取微信平台传过来的请求参数【PS：默认是XML格式的，这里转化成了Mapl类型】
        Map<String, String> receiveMap = TransformUtils.xml2Map(request);
        log.info("接收微信消息时获取到的信息为：" + receiveMap);

//        04 从Map对象中获取单个数据
        String fromUserName = receiveMap.get("FromUserName");
        String toUserName = receiveMap.get("ToUserName");
        String msgType = receiveMap.get("MsgType");

//        05 用于存放String类型的XML格式响应数据
        String message = null;
//        06 如果接收的消息类型是text类型的处理逻辑
        if (MessageTypeEnum.RECEIVE_MESSAGE_TEXT.getType().equals(msgType)) {
            message = receiveMessageService.textMessageHandler(receiveMap);
        }
//        07 响应对象非空处理，如果返回null会报异常（影响用户体验）
        if (message == null) {
            message = "";
        }
//        08 打印XML格式的响应消息
        log.info("被动回复消息的XML格式为：" + message);
//        09 响应XML格式数据给微信服务器
        out.print(message);

    }

}

